package com.liwen.web.exception;

import com.liwen.service.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: li.wen
 * @time: 2017-09-25 17:36
 * @description: 处理reponsebody返回值出现异常的情况
 */
@RestControllerAdvice(basePackages = {"com.liwen.web.controller.rest"})
public class RestExceptionHandler {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 未知错误
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Map<String, Object> ex(HttpServletRequest req, Exception e) {
        log.error("ex-uri:{},msg:{}", req.getRequestURI(), e.getMessage());
        Map<String, Object> map = new HashMap<>();
        map.put("code", "500");
        map.put("msg", "系统错误");
        return map;
    }
    /**
     * 业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    public Map<String, Object> biz(HttpServletRequest req, BizException e) {
        log.error("biz-uri:{},msg:{}", req.getRequestURI(), e.getMessage());
        Map<String, Object> map = new HashMap<>();
        map.put("code", e.getCode());
        map.put("msg", e.getMessage());
        return map;
    }
}
